package development.game;

import java.util.Vector;

import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.TimerListener;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.DataReceiveListener;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.NumberUtil;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.bean.CardInfo;
import development.bean.Game;
import development.group.FrmGroupListTableFreeUserChat;
import development.group.FrmGroupTableFreeUserFriend;
import development.socket.SocketClientUtil;

public class FrmTLMB extends GameForm implements DataReceiveListener, TimerListener {
  private final int TIME_COUNT = 30;
  private final int khoangCachXemBai = 15;

  private final int CHIABAI_HEARDER = 4002;
  private final int LUOTCHOI_HEARDER = 4003;
  private final int DANHBAI_HEARDER = 4004;
  private final int KHONGHOPLE_HEARDER = 4005;
  private final int KHONG_PHAI_BE_NHAT_HEARDER = 4006;
  private final int DANHBAI_SUCCESS_HEARDER = 4007;
  private final int BO_LUOT_HEARDER = 4009;
  private final int DS_USERS_HEARDER = 4010;
  private final int HET_BAI_HEARDER = 4011;
  private final int THOI_2_HEARDER = 4012;
  private final int THOI_TU_QUY_HEARDER = 4013;
  private final int PHAI_DANH_HEARDER = 4014;
  private final int INTERUPT_HEARDER = 4015;
  private final int KHONG_DUOC_DANH_2_SAU_CUNG_HEARDER = 4016;
  private final int BANG_KQ_HEARDER = 4017;
  private static final int MONEY_CHANGE_NOTIFY_HEADER = 4022;
  private static final int INIT_FOR_VIEW_USER_HEADER = 4023;
  private static final int USER_VIEW_JOIN_HEADER = 4024;

  private final int DANH_BAI = 1;
  private final int CHON_DANH_BAI = 2;
  private final int CHON_BO_LUOT = 3;
  private final int MENU = 4;
  private final int CARD_WIDTH = 55;
  
  private final int[][][] USER_INFO_LOCATION_240x320 = new int[][][] 
    {
      {{140, 190}, null,       {140, 0}, null},
      {{140, 190}, {240, 140}, {140, 0}, null},
      {{140, 190}, {240, 140}, {140, 0}, {70, 140}}
    };
   
   private final int[][][] USER_INFO_LOCATION_320x240 = new int[][][] 
    {
      {{180, 140}, null,       {180, 0}, null},
      {{180, 140}, {320, 100}, {180, 0}, null},
      {{180, 140}, {320, 100}, {180, 0}, {70, 100}}
    };
   
   private final boolean[][] IS_INFO_RIGHT_TO_LEFT = new boolean[][]
    {
     {true, true, true, true},
     {true, true, true, true},
     {true, true, true, true}
    };
   
//   private final int[][][] CHAT_LOCATION_240x320 = new int[][][] 
//   {
//     {{140, 190}, {140, 0}},
//     {{140, 190}, {140, 140}, {140, 0}},
//     {{140, 190}, {140, 140}, {140, 0}, {0, 140}}
//   };
//
//   private final int[][][] CHAT_LOCATION_320x240 = new int[][][] 
//   {
//     {{180, 140}, {180, 0}},
//     {{180, 140}, {220, 100}, {180, 0}},
//     {{180, 140}, {220, 100}, {180, 0}, {0, 100}}
//   };

  private GameImage baiUpImage;
  private GameImage arrowImage;

  private GameImage[] ketQuaImg;

  private GameImage nhatImg;
  private GameImage[] cardImges;
  private GameImage[] baiMatSauImages;
  private GameImage chuyenLuotImg;

  private GameImage tableImage;

  private Vector[] userCards;
  private String[] playerNames;
  private int[] resultIndex;
  
  private String nguoiThoatGame;
  private int soNguoiChoi;
  private int state;

  private Vector baiDanhRa;
  private int movePointer;
  private int soQuanBaiDanhRa;
  private boolean isHopLe;
  private boolean isCoTheBoLuot;
  private boolean isNot2SauCung;
  private boolean isShow3BichWarning;

  private int time;
  private int countTime;

  private String thoi2;
  private String thoiTuQuy;
  private boolean isKetThucVan;
  private String kqTen[];
  private String kqThuHang[];
  private String kqMoney[];
  private int[][] userInfoLocation;
  private boolean[] isInfoRightToLeft;
  private int currentTurnIndex;
  private ImageText text8;
  private String[] cardOrder;
  private String moneyChangeMessage = "";
  private int moneyChangeIndex;
  private boolean isClientInitDone = false;
  
  private StringArray initData;
  private StringArray chiaBaiData;
  private String luotChoiData;
  private boolean isViewUser;
  
  private static GameForm singleton;
  
  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmTLMB();
    }
    return singleton;
  }
  
  public void init(Hashtable inputParameters) {
    isViewUser = false;
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    
    baiDanhRa = new Vector();
    state = 0;
    movePointer = 0;
    soQuanBaiDanhRa = 0;
    moneyChangeMessage = "";
    moneyChangeIndex = -1;
    isHopLe = true;
    isCoTheBoLuot = true;
    thoi2 = "";
    thoiTuQuy = "";
    isKetThucVan = false;
    isNot2SauCung = true;
    isShow3BichWarning = true;

    chuyenLuotImg = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "Nen_So.png");
    tableImage = ImageUtil.getImage(Constants.CARD_IMAGE_CATEGORY, "bg_Danh-bai.png");
    GameImage backButtonImage = ImageUtil.getImage(Constants.CARD_IMAGE_CATEGORY, "button_back.png");
    arrowImage = ImageUtil.rotate(backButtonImage, 90);

    // Khởi tạo các ảnh quân bài
    cardOrder = new String[]{"Bich", "Nhep", "Ro", "Co"};
    cardImges = new GameImage[52];

    ketQuaImg = new GameImage[4];
    ketQuaImg[0] = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "mom.png");
    ketQuaImg[1] = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "Nhi.png");
    ketQuaImg[2] = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "Ba.png");
    ketQuaImg[3] = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "Bet.png");
    nhatImg = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "Nhat.png");

    baiMatSauImages = new GameImage[3];
    baiMatSauImages[0] = ImageUtil.getImage(Constants.CARD_IMAGE_CATEGORY, "Bai_MSau.png");
    baiMatSauImages[1] = ImageUtil.rotate(baiMatSauImages[0], 90);
    baiMatSauImages[2] = ImageUtil.rotate(baiMatSauImages[0], 270);
    baiUpImage = baiMatSauImages[0];
    
    time = TIME_COUNT;
    countTime = 0;
    resultIndex = new int[4];
    kqMoney = null;
    kqTen = null;
    kqThuHang = null;
    setTimerListener(this);
    DrawUtils.setBottomBar(_manager, "", "", "Trở về");
    _manager.enableTouchPad();
    
    isClientInitDone = true;
    if (initData != null) {
      initForGame(initData);
    }
    
    if (chiaBaiData != null) {
      chiaBai(chiaBaiData);
    }
    
    if (luotChoiData != null) {
      luotChoi(luotChoiData);
    }
  }
  
  private void prepareDrawLocation(int numberOfPlayer) {
    if (GameConstants.IS_240x320_SCREEN) {
      userInfoLocation = USER_INFO_LOCATION_240x320[numberOfPlayer - 2];
    } else {
      userInfoLocation = USER_INFO_LOCATION_320x240[numberOfPlayer - 2];
    }
 // TODO: disable chat of game TLMB
//    Global.initChatComponent(CHAT_LOCATION_240x320[numberOfPlayer - 2], CHAT_LOCATION_320x240[numberOfPlayer - 2]);
    isInfoRightToLeft = IS_INFO_RIGHT_TO_LEFT[numberOfPlayer - 2];
  }

  private void luotChoi(String strData) {
    time = TIME_COUNT;
    if (Global.currentUser.getName().equals(strData)) {
      currentTurnIndex = 0;
    } else if (strData.equals(playerNames[2])) {
      currentTurnIndex = 2;
    } else if (strData.equals(playerNames[1])) {
      currentTurnIndex = 1;
    } else if (strData.equals(playerNames[3])) {
      currentTurnIndex = 3;
    }
  }

  private void initForGame(StringArray usersList) {
    if (!isClientInitDone) {
      initData = usersList;
      return;
    }
    
    soNguoiChoi = usersList.len();
    prepareDrawLocation(soNguoiChoi);
    playerNames = new String[] {Global.currentUser.getName(), "", "", ""};
    if (soNguoiChoi == 2) {
      String name0 = usersList.array[0];
      String name1 = usersList.array[1];
      if (Global.currentUser.getName().equalsIgnoreCase(name0)) {
        playerNames[2] = name1;
      } else {
        playerNames[2] = name0;
      }
    } else if (soNguoiChoi == 3) {
      String name0 = usersList.array[0];
      String name1 = usersList.array[1];
      String name2 = usersList.array[2];
      if (Global.currentUser.getName().equalsIgnoreCase(name0)) {
        playerNames[1] = name1;
        playerNames[2] = name2;
      } else if (Global.currentUser.getName().equalsIgnoreCase(name1)) {
        playerNames[2] = name0;
        playerNames[1] = name2;
      } else if (Global.currentUser.getName().equalsIgnoreCase(name2)) {
        playerNames[2] = name1;
        playerNames[1] = name0;
      }
    } else if (soNguoiChoi == 4) {
      String name0 = usersList.array[0];
      String name1 = usersList.array[1];
      String name2 = usersList.array[2];
      String name3 = usersList.array[3];
      if (Global.currentUser.getName().equalsIgnoreCase(name0)) {
        playerNames[1] = name1;
        playerNames[2] = name2;
        playerNames[3] = name3;
      } else if (Global.currentUser.getName().equalsIgnoreCase(name1)) {
        playerNames[2] = name3;
        playerNames[1] = name2;
        playerNames[3] = name0;
      } else if (Global.currentUser.getName().equalsIgnoreCase(name2)) {
        playerNames[1] = name3;
        playerNames[2] = name0;
        playerNames[3] = name1;
      } else if (Global.currentUser.getName().equalsIgnoreCase(name3)) {
        playerNames[1] = name0;
        playerNames[2] = name1;
        playerNames[3] = name2;
      }
    }
  }
  
  private void initForViewUser(DataPackage dataPackage) {
    isViewUser = true;
    userCards = new Vector[4];
    for (int i = 0; i < 4; i++) {
      userCards[i] = new Vector();
    }
    
    // Init players
    int size = dataPackage.nextInt();
    for (int i = 0; i < size; i++) {
      String username = dataPackage.nextString();
      int numberOfCard = dataPackage.nextInt();
      for (int j = 0; j < 4; j++) {
        if (username.equals(playerNames[j])) {
          userCards[j].setSize(numberOfCard);
          continue;
        }
      }
    }
    
    // Init luot choi
    luotChoi(dataPackage.nextString());
    
    // Init fired card
    int fireCardSize = dataPackage.nextInt();
    if (fireCardSize > 0) {
      baiDanhRa = new Vector();
      for (int i = 0; i < fireCardSize; i++) {
        baiDanhRa.addElement(String.valueOf(dataPackage.nextInt()));
      }
    }
    
    // Init for chat
    // TODO: disable chat of game TLMB
//    SocketClientUtil.joinChatRoom(CHAT_LOCATION_240x320[soNguoiChoi - 2], CHAT_LOCATION_320x240[soNguoiChoi - 2]);
  }
  
  private void chiaBai(StringArray str) {
    userCards = new Vector[4];
    for (int i = 0; i < 4; i++) {
      userCards[i] = new Vector();
    }
    for (int i = 0; i < str.len(); i++) {
      CardInfo card = new CardInfo();
      card.setQuanBai(NumberUtil.parseInt(str.array[i]));
      userCards[0].addElement(card);
    }
    if (soNguoiChoi == 2) {
      userCards[2].setSize(13);
    } else if (soNguoiChoi == 3) {
      userCards[2].setSize(13);
      userCards[1].setSize(13);
    } else if (soNguoiChoi == 4) {
      userCards[2].setSize(13);
      userCards[1].setSize(13);
      userCards[3].setSize(13);
    }
  }
  
  private void onUserViewJoin(DataPackage dataPackage) {
    String userJoin = dataPackage.nextString();
    for (int i = 0; i < 4; i++) {
      if ("".equals(playerNames[i])) {
        playerNames[i] = userJoin;
        break;
      }
    }
    soNguoiChoi++;
    if (soNguoiChoi > 4) {
      soNguoiChoi = 4;
    }
    prepareDrawLocation(soNguoiChoi);
  }
  
  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    
    if (header == DS_USERS_HEARDER) {
      dataPackage.nextString(); // from User
      String strData = dataPackage.nextString();
      StringArray str = GameStringUtils.split(strData, ":");
      initForGame(str);
    } else if (header == INIT_FOR_VIEW_USER_HEADER) {
      initForViewUser(dataPackage);
    } else if (header == USER_VIEW_JOIN_HEADER) {
      onUserViewJoin(dataPackage);
    } else if (header == MONEY_CHANGE_NOTIFY_HEADER) {
      String username1 = dataPackage.nextString();
      int changedMoney1 = dataPackage.nextInt();
      if (username1.equals(Global.currentUser.getName())) {
        if (changedMoney1 > 0) {
          moneyChangeMessage = "Thưởng " + changedMoney1 + " gold";
        } else {
          moneyChangeMessage = "Trừ " + Math.abs(changedMoney1) + " gold";
        }
        moneyChangeIndex = 0;
      }
    } else if (header == CHIABAI_HEARDER) {
      dataPackage.nextString(); // from User
      String strData = dataPackage.nextString();
      StringArray str = GameStringUtils.split(strData, ":");
      if (!isClientInitDone) {
        chiaBaiData = str;
        return;
      }
      chiaBai(str);
    } else if (header == LUOTCHOI_HEARDER) {
      dataPackage.nextString(); // from User
      String strData = dataPackage.nextString();
      if (!isClientInitDone) {
        luotChoiData = strData;
        return;
      }
      luotChoi(strData);
    } else if (header == PHAI_DANH_HEARDER) {
      isCoTheBoLuot = false;
    } else if (header == INTERUPT_HEARDER) {
      dataPackage.nextString(); // from User
      String leftUser = dataPackage.nextString();
      if (Global.currentUser.getName().equals(leftUser)) {
        playerNames[0] = "";
        resultIndex[0] = 0;
      } else if (leftUser.equals(playerNames[2])) {
        playerNames[2] = "";
        resultIndex[2] = 0;
      } else if (leftUser.equals(playerNames[1])) {
        playerNames[1] = "";
        resultIndex[1] = 0;
      } else if (leftUser.equals(playerNames[3])) {
        playerNames[3] = "";
        resultIndex[3] = 0;
      }
    } else if (header == DANHBAI_SUCCESS_HEARDER) {
      dataPackage.nextString(); // from User
      String strData = dataPackage.nextString();
      isCoTheBoLuot = true;
      StringArray str = GameStringUtils.split(strData, ":");
      baiDanhRa = new Vector();
      for (int i = 0; i < str.len(); i++) {
        baiDanhRa.addElement(str.array[i]);
      }
      if (currentTurnIndex == 0) {
        movePointer = 0;
        for (int j = 0; j < baiDanhRa.size(); j++) {
          removeCard(userCards[0], NumberUtil.parseInt(baiDanhRa.elementAt(j).toString()));
        }
      } else {
        if (userCards[currentTurnIndex].size() - baiDanhRa.size() >= 0) {
          userCards[currentTurnIndex].setSize(userCards[currentTurnIndex].size() - baiDanhRa.size());
        }
      }
    } else if (header == KHONGHOPLE_HEARDER) {
      isHopLe = false;
    } else if (header == KHONG_PHAI_BE_NHAT_HEARDER) {
      isShow3BichWarning = false;
    } else if (header == HET_BAI_HEARDER) {
      dataPackage.nextString(); // from User
      String strData = dataPackage.nextString();
      StringArray str = GameStringUtils.split(strData, ":");
      if (str.array[0].equals(Global.currentUser.getName())) {
        resultIndex[0] = NumberUtil.parseInt(str.array[1]);
      } else if (str.array[0].equals(playerNames[2])) {
        resultIndex[2] = NumberUtil.parseInt(str.array[1]);
        userCards[2].setSize(0);
      } else if (str.array[0].equals(playerNames[1])) {
        resultIndex[1] = NumberUtil.parseInt(str.array[1]);
        userCards[1].setSize(0);
      } else if (str.array[0].equals(playerNames[3])) {
        resultIndex[3] = NumberUtil.parseInt(str.array[1]);
        userCards[3].setSize(0);
      }
    } else if (header == THOI_2_HEARDER) {
      dataPackage.nextString(); // from User
      String strData = dataPackage.nextString();
      thoi2 = strData;
    } else if (header == THOI_TU_QUY_HEARDER) {
      dataPackage.nextString(); // from User
      String strData = dataPackage.nextString();
      thoiTuQuy = strData;
    } else if (header == KHONG_DUOC_DANH_2_SAU_CUNG_HEARDER) {
      isNot2SauCung = false;
    } else if (header == BANG_KQ_HEARDER) {
      dataPackage.nextString(); // from User
      String strData = dataPackage.nextString();
      StringArray strTemp = GameStringUtils.split(strData, ":");
      kqTen = new String[strTemp.len()];
      kqThuHang = new String[strTemp.len()];
      kqMoney = new String[strTemp.len()];
      for (int i = 0; i < strTemp.len(); i++) {
        StringArray strT = GameStringUtils.split(strTemp.array[i], "|");
        kqTen[i] = strT.array[0];
        kqThuHang[i] = getThuHang(strT.array[1]);
        kqMoney[i] = strT.array[2];
        
        if (Global.currentUser.getName().equals(kqTen[i])) {
          int changedMoney1 = NumberUtil.parseInt(kqMoney[i]);
          if (changedMoney1 > 0) {
            moneyChangeMessage = "Thưởng " + changedMoney1 + " gold";
          } else {
            moneyChangeMessage = "Trừ " + Math.abs(changedMoney1) + " gold";
          }
          moneyChangeIndex = 0;
        }
      }
      isKetThucVan = true;
    }
  }
  
  private void removeCard(Vector cardInfos, int cardToRemove) {
    for (int i = 0; i < cardInfos.size(); i++) {
      CardInfo card = (CardInfo) cardInfos.elementAt(i);
      if (card.getQuanBai() == cardToRemove) {
        cardInfos.removeElementAt(i);
        return;
      }
    }
  }

  public void draw(Graphics g) {
    DrawUtils.drawBackground(g);
    g.drawImage(tableImage, Constants.SCREEN_WIDTH / 2, (Constants.SCREEN_HEIGHT - 25) / 2, Constants.CENTER_ANCHOR);
    drawUserInfo(g);
    if (GameConstants.IS_240x320_SCREEN) {
      drawUserCard(g);
    } else {
      drawUserCard320(g);
    }
    
    drawOponentCards(g);
    drawDanhBai(g);
    drawCayThoi(g);
    
    if (GameConstants.IS_240x320_SCREEN) {
      drawCountTime(g);
    } else {
      drawCountTime320(g);
    }
    drawNguoiThoatGame(g);
    drawMoneyChangeNotification(g);
    
    drawMenu(g);
    Global.drawChat(g);
    drawKetQua(g);
  }

  public void keyReleased(int keyCode) {
    if (!Key.isCommandKey) {
      if (Global.chatComponent != null) {
        Global.chatComponent.setShowInputChatMessageTextField(true);
        Global.chatComponent.keyReleased(keyCode);
      }
      return;
    }
    
    switch (keyCode) {
    case Key.LEFT:
    case Key.K_4:
      if (isViewUser) {
        return;
      }
      
      isHopLe = true;
      isShow3BichWarning = true;
      nguoiThoatGame = "";
      isCoTheBoLuot = true;
      isNot2SauCung = true;
      if (state == MENU || isKetThucVan) {
        return;
      }
      CardInfo temp1 = null;
      int move1 = 0;
      if (((CardInfo) userCards[0].elementAt(movePointer)).getQuanDiChuyen() != -1) {
        temp1 = (CardInfo) userCards[0].elementAt(movePointer);
        move1 = movePointer;
      }

      movePointer--;
      if (movePointer < 0) {
        movePointer = userCards[0].size() - 1;
      }

      if (temp1 != null) {
        userCards[0].setElementAt(userCards[0].elementAt(movePointer), move1);
        userCards[0].setElementAt(temp1, movePointer);
      }
      break;
    case Key.RIGHT:
    case Key.K_2:
      if (isViewUser) {
        return;
      }
      
      isHopLe = true;
      isShow3BichWarning = true;
      nguoiThoatGame = "";
      isCoTheBoLuot = true;
      isNot2SauCung = true;
      if (state == MENU || isKetThucVan) {
        return;
      }
      CardInfo temp = null;
      int move = 0;
      if (((CardInfo) userCards[0].elementAt(movePointer)).getQuanDiChuyen() != -1) {
        temp = (CardInfo) userCards[0].elementAt(movePointer);
        move = movePointer;
      }

      movePointer++;
      if (movePointer > userCards[0].size() - 1) {
        movePointer = 0;
      }
      if (temp != null) {
        userCards[0].setElementAt(userCards[0].elementAt(movePointer), move);
        userCards[0].setElementAt(temp, movePointer);
      }
      break;
    case Key.FIRE:
    case Key.K_5:
      if (Global.isShowedInputChatBox()) {
        SocketClientUtil.sendMessage(Global.chatComponent.getCurrentRoomId(), Global.chatComponent.getChatTextField().getText());
        Global.hideInputChatBox();
        return;
      }
      
      isHopLe = true;
      isShow3BichWarning = true;
      nguoiThoatGame = "";
      isCoTheBoLuot = true;
      isNot2SauCung = true;

      if (isKetThucVan) {
        GameGlobal.nextState(FrmGroupTableFreeUserFriend.instance(), null);
        return;
      }
      
      if (isViewUser) {
        return;
      }

      if (currentTurnIndex != 0) {
        return;
      }

      for (int i = 0; i < userCards[0].size(); i++) {
        if (((CardInfo) userCards[0].elementAt(i)).getQuanChon() != -1) {
          setState(CHON_DANH_BAI);
          break;
        } else {
          setState(CHON_BO_LUOT);
        }
      }
      if (state == CHON_DANH_BAI) {
        setState(DANH_BAI);
      } else if (state == CHON_BO_LUOT) {
        sendMessageAction(BO_LUOT_HEARDER, Global.currentUser.getName());
      }
      break;
    case Key.UP:
      if (isViewUser) {
        return;
      }

      isHopLe = true;
      isShow3BichWarning = true;
      nguoiThoatGame = "";
      isCoTheBoLuot = true;
      isNot2SauCung = true;
      if (isKetThucVan) {
        return;
      }
      if (userCards[0] != null && userCards[0].size() > 0) {
        if (((CardInfo) userCards[0].elementAt(movePointer)).getQuanDiChuyen() == -1) {
          ((CardInfo) userCards[0].elementAt(movePointer)).setQuanChon(movePointer);
          setState(CHON_DANH_BAI);
        } else {
          ((CardInfo) userCards[0].elementAt(movePointer)).setQuanChon(-1);
          ((CardInfo) userCards[0].elementAt(movePointer)).setQuanDiChuyen(-1);
        }
      }
      break;
    case Key.DOWN:
      if (isViewUser) {
        return;
      }
      
      isHopLe = true;
      isShow3BichWarning = true;
      isCoTheBoLuot = true;
      nguoiThoatGame = "";
      isNot2SauCung = true;
      if (isKetThucVan) {
        return;
      }
      if (userCards[0] != null && userCards[0].size() > 0) {
        if (((CardInfo) userCards[0].elementAt(movePointer)).getQuanChon() != -1) {
          ((CardInfo) userCards[0].elementAt(movePointer)).setQuanChon(-1);
        } else {
          ((CardInfo) userCards[0].elementAt(movePointer)).setQuanDiChuyen(movePointer);
          ((CardInfo) userCards[0].elementAt(movePointer)).setQuanChon(-1);
        }
      }
      for (int i = 0; i < userCards[0].size(); i++) {
        if (((CardInfo) userCards[0].elementAt(i)).getQuanChon() != -1) {
          setState(CHON_DANH_BAI);
          break;
        } else {
          setState(CHON_BO_LUOT);
        }
      }
      break;
    case Key.SOFT_LEFT:
      if (Global.isShowedInputChatBox()) {
        Global.hideInputChatBox();
      } else {
        isHopLe = true;
        isShow3BichWarning = true;
        nguoiThoatGame = "";
        isCoTheBoLuot = true;
        isNot2SauCung = true;
      }
      break;
    case Key.SOFT_RIGHT:
      if (Global.isShowedInputChatBox()) {
        Global.chatComponent.getChatTextField().deleteLastChar();
      } else {
        isHopLe = true;
        isCoTheBoLuot = true;
        nguoiThoatGame = "";
        isNot2SauCung = true;
        if (isKetThucVan) {
          SocketClientUtil.leaveTableRequest();
          GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
        } else if (isViewUser) {
          SocketClientUtil.leaveTableRequest();
          GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
        } else {
          Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create2("Bạn có muốn thoát?", "Bạn sẽ bị xử bét", "nếu thoát giữa chừng"), 93);
        }
      }
      break;
    }
  }
  
  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if ((alertId == 93) && (eventType == GameAlert.YES_BUTTON)) {
      SocketClientUtil.leaveTableRequest();
      GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
    }
  }

  private void drawMenu(Graphics g) {
    if (isKetThucVan) {
      DrawUtils.setBottomBar(_manager, "", "Chơi tiếp", "Thoát");
    } else {
      if (currentTurnIndex == 0) {
        if (state == CHON_DANH_BAI) {
          DrawUtils.setBottomBar(_manager, "", "Đánh", "Trở về");
        } else {
          if (isViewUser) {
            DrawUtils.setBottomBar(_manager, "", "", "Trở về");
          } else {
            DrawUtils.setBottomBar(_manager, "", "Bỏ lượt", "Trở về");
          }
        }
      } else {
        DrawUtils.setBottomBar(_manager, "", "", "Trở về");
      }
    }
  }

  private void drawCayThoi(Graphics g) {
    if (!isNot2SauCung) {
      DrawUtils.drawNotification(g, "Không được đánh 2 sau cùng!", text8);
    }
    
    // Nếu thối 2
    if (thoi2 != null && thoi2.length() > 0) {
      DrawUtils.drawNotification(g, "Thối: " + thoi2 + " cây 2", text8);
    }
    
    // Nếu thối tứ quý
    if (thoiTuQuy != null && thoiTuQuy.length() > 0) {
      DrawUtils.drawNotification(g, "Thối: " + thoiTuQuy + " tứ quý", text8);
    }
  }

  private void drawNguoiThoatGame(Graphics g) {
    if (nguoiThoatGame != null && nguoiThoatGame.length() > 0) {
      DrawUtils.drawNotification(g, nguoiThoatGame + " đã thoát game", text8);
    }
  }

  private void drawKetQua(Graphics g) {
    if (resultIndex == null) {
      return;
    }

    if (resultIndex[0] == 1) {
      g.drawImage(nhatImg, GameConstants.SCREEN_WIDTH / 2 + 5, GameConstants.SCREEN_HEIGHT - 97, GameConstants.TOP_HCENTER_ANCHOR);
    } else if (resultIndex[0] == 2) {
      g.drawImage(ketQuaImg[1], GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT - 107, GameConstants.TOP_HCENTER_ANCHOR);
    } else if (resultIndex[0] == 3) {
      g.drawImage(ketQuaImg[2], GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT - 107, GameConstants.TOP_HCENTER_ANCHOR);
    } else if (resultIndex[0] == 4) {
      g.drawImage(ketQuaImg[3], GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT - 107, GameConstants.TOP_HCENTER_ANCHOR);
    }
    
    if (resultIndex[2] == 1) {
      g.drawImage(nhatImg, GameConstants.SCREEN_WIDTH / 2 + 5, 16, GameConstants.TOP_HCENTER_ANCHOR);
    } else if (resultIndex[2] == 2) {
      g.drawImage(ketQuaImg[1], GameConstants.SCREEN_WIDTH / 2, 8, GameConstants.TOP_HCENTER_ANCHOR);
    } else if (resultIndex[2] == 3) {
      g.drawImage(ketQuaImg[2], GameConstants.SCREEN_WIDTH / 2, 8, GameConstants.TOP_HCENTER_ANCHOR);
    } else if (resultIndex[2] == 4) {
      g.drawImage(ketQuaImg[3], GameConstants.SCREEN_WIDTH / 2, 8, GameConstants.TOP_HCENTER_ANCHOR);
    }

    if (resultIndex[1] == 1) {
      g.drawImage(nhatImg, GameConstants.SCREEN_WIDTH - 74, 80, GameConstants.TOP_LEFT_ANCHOR);
    } else if (resultIndex[1] == 2) {
      g.drawImage(ketQuaImg[1], GameConstants.SCREEN_WIDTH - 80, 70, GameConstants.TOP_LEFT_ANCHOR);
    } else if (resultIndex[1] == 3) {
      g.drawImage(ketQuaImg[2], GameConstants.SCREEN_WIDTH - 80, 70, GameConstants.TOP_LEFT_ANCHOR);
    } else if (resultIndex[1] == 4) {
      g.drawImage(ketQuaImg[3], GameConstants.SCREEN_WIDTH - 80, 70, GameConstants.TOP_LEFT_ANCHOR);
    }

    if (resultIndex[3] == 1) {
      g.drawImage(nhatImg, 44, 80, GameConstants.TOP_LEFT_ANCHOR);
    } else if (resultIndex[3] == 2) {
      g.drawImage(ketQuaImg[1], 39, 70, GameConstants.TOP_LEFT_ANCHOR);
    } else if (resultIndex[3] == 3) {
      g.drawImage(ketQuaImg[2], 39, 70, GameConstants.TOP_LEFT_ANCHOR);
    } else if (resultIndex[3] == 4) {
      g.drawImage(ketQuaImg[3], 39, 70, GameConstants.TOP_LEFT_ANCHOR);
    }
    if (resultIndex[0] > 0) {
      DrawUtils.setBottomBar(_manager, "", "Chơi lại", "Thoát");
    }
  }

  private void drawUserCard(Graphics g) {
    if (userCards == null) {
      return;
    }
    
    // Vẽ bài người chơi
    int pointerY = 270;
    for (int i = 0; i < userCards[0].size(); i++) {
      int y = 270;
      if (((CardInfo) userCards[0].elementAt(i)).getQuanDiChuyen() != -1) {
        y = 270;
      } else if (((CardInfo) userCards[0].elementAt(i)).getQuanChon() != -1) {
        y = 235;
      } else {
        y = 260;
      }
      if (i == movePointer) {
        pointerY = y - 12;
      }
      drawCardImage(g, ((CardInfo) userCards[0].elementAt(i)).getQuanBai(), GameConstants.SCREEN_WIDTH / 2 - (userCards[0].size() * khoangCachXemBai + CARD_WIDTH) / 2 + (i + 1) * khoangCachXemBai, y, GameConstants.TOP_LEFT_ANCHOR, false);
    }

    if (userCards[0] != null && userCards[0].size() > 0) {
      g.drawImage(arrowImage, GameConstants.SCREEN_WIDTH / 2 - (userCards[0].size() * khoangCachXemBai + CARD_WIDTH) / 2 + 5 + khoangCachXemBai * (movePointer + 1), pointerY, GameConstants.CENTER_ANCHOR);
    }
  }

  private void drawUserCard320(Graphics g) {
    // Vẽ bài người chơi
    int pointerY = 190;
    for (int i = 0; i < userCards[0].size(); i++) {
      int y = 190;
      if (((CardInfo) userCards[0].elementAt(i)).getQuanDiChuyen() != -1) {
        y = 190;
      } else if (((CardInfo) userCards[0].elementAt(i)).getQuanChon() != -1) {
        y = 155;
      } else {
        y = 180;
      }
      if (i == movePointer) {
        pointerY = y - 12;
      }
      drawCardImage(g, ((CardInfo) userCards[0].elementAt(i)).getQuanBai(), GameConstants.SCREEN_WIDTH / 2 - (userCards[0].size() * khoangCachXemBai + CARD_WIDTH) / 2 + (i + 1) * khoangCachXemBai, y, GameConstants.TOP_LEFT_ANCHOR, false);
    }

    if (userCards[0] != null && userCards[0].size() > 0) {
      g.drawImage(arrowImage, GameConstants.SCREEN_WIDTH / 2 - (userCards[0].size() * khoangCachXemBai + CARD_WIDTH) / 2 + 5 + khoangCachXemBai * (movePointer + 1), pointerY, GameConstants.CENTER_ANCHOR);
    }
  }

  private void drawOponentCards(Graphics g) {
    if (soNguoiChoi == 2) {
      if (playerNames[2].length() > 0 && userCards[2].size() > 0) {
        g.drawImage(baiMatSauImages[0], Constants.SCREEN_WIDTH / 2, 25, GameConstants.BOTTOM_HCENTER_ANCHOR);
        text8.drawString2(g, "" + userCards[2].size(), GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 20, GameConstants.BOTTOM_HCENTER_ANCHOR);
      }
    } else if (soNguoiChoi == 3) {
      if (playerNames[2].length() > 0 && userCards[2].size() > 0) {
        g.drawImage(baiMatSauImages[0], Constants.SCREEN_WIDTH / 2, 25, GameConstants.BOTTOM_HCENTER_ANCHOR);
        text8.drawString2(g, "" + userCards[2].size(), GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 20, GameConstants.BOTTOM_HCENTER_ANCHOR);
      }
      if (playerNames[1].length() > 0 && userCards[1].size() > 0) {
        g.drawImage(baiMatSauImages[1], Constants.SCREEN_WIDTH - 25, (Constants.SCREEN_HEIGHT - 25) / 2, GameConstants.VCENTER_LEFT_ANCHOR);
        text8.drawString2(g, "" + userCards[1].size(), GameColor.WHITE_CODE, Constants.SCREEN_WIDTH - 20, (Constants.SCREEN_HEIGHT - 25) / 2, GameConstants.VCENTER_LEFT_ANCHOR);
      }
    } else if (soNguoiChoi == 4) {
      if (playerNames[2].length() > 0 && userCards[2].size() > 0) {
        g.drawImage(baiMatSauImages[0], Constants.SCREEN_WIDTH / 2, 25, GameConstants.BOTTOM_HCENTER_ANCHOR);
        text8.drawString2(g, "" + userCards[2].size(), GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 20, GameConstants.BOTTOM_HCENTER_ANCHOR);
      }
      if (playerNames[1].length() > 0 && userCards[1].size() > 0) {
        g.drawImage(baiMatSauImages[1], Constants.SCREEN_WIDTH - 25, (Constants.SCREEN_HEIGHT - 25) / 2, GameConstants.VCENTER_LEFT_ANCHOR);
        text8.drawString2(g, "" + userCards[1].size(), GameColor.WHITE_CODE, Constants.SCREEN_WIDTH - 20, (Constants.SCREEN_HEIGHT - 25) / 2, GameConstants.VCENTER_LEFT_ANCHOR);
      }
      if (playerNames[3].length() > 0 && userCards[3].size() > 0) {
        g.drawImage(baiMatSauImages[2], 25, (Constants.SCREEN_HEIGHT - 25) / 2, GameConstants.VCENTER_RIGHT_ANCHOR);
        text8.drawString2(g, "" + userCards[3].size(), GameColor.WHITE_CODE, 20, (Constants.SCREEN_HEIGHT - 25) / 2, GameConstants.VCENTER_RIGHT_ANCHOR);
      }
    }
  }

  private void drawUserInfo(Graphics g) {
    if (playerNames == null) {
      return;
    }
    for (int i = 0; i < 4; i++) {
      if ((playerNames[i] != null) && !"".equals(playerNames[i])) {
        DrawUtils.drawUserInfo(g, playerNames[i], userInfoLocation[i][0], userInfoLocation[i][1], isInfoRightToLeft[i]);  
      }
    } 
  }

  private void drawCountTime(Graphics g) {
    if (isKetThucVan) {
      return;
    }
    
    if ((playerNames[currentTurnIndex] == null) || (playerNames[currentTurnIndex].length() == 0)) {
      return;
    }
    
    int x = 0;
    int y = 0;
    if (currentTurnIndex == 0) {  
      text8.drawString2(g, String.valueOf(time), 0xffffff, Constants.SCREEN_WIDTH / 2, 234, GameConstants.TOP_HCENTER_ANCHOR);
      x = Constants.SCREEN_WIDTH / 2;
      y = 232;
    } else if (currentTurnIndex == 2) {
      x = Constants.SCREEN_WIDTH / 2;
      y = 35;
    } else if (currentTurnIndex == 1) {
      x = 195;
      y = (Constants.SCREEN_HEIGHT - 25) / 2;
    } else if (currentTurnIndex == 3) {
      x = 45;
      y = (Constants.SCREEN_HEIGHT - 25) / 2;
    }
    g.drawImage(chuyenLuotImg, x, y, GameConstants.TOP_HCENTER_ANCHOR);
    text8.drawString2(g, String.valueOf(time), 0xffffff, x, y + 2, GameConstants.TOP_HCENTER_ANCHOR);
  }

  private void drawCountTime320(Graphics g) {
    if (isKetThucVan) {
      return;
    }
    
    if ((playerNames[currentTurnIndex] == null) || (playerNames[currentTurnIndex].length() == 0)) {
      return;
    }
    
    int x = 0;
    int y = 0;
    if (currentTurnIndex == 0) {  
      text8.drawString2(g, String.valueOf(time), 0xffffff, Constants.SCREEN_WIDTH / 2, 234, GameConstants.TOP_HCENTER_ANCHOR);
      x = Constants.SCREEN_WIDTH / 2;
      y = 160;
    } else if (currentTurnIndex == 2) {
      x = Constants.SCREEN_WIDTH / 2;
      y = 35;
    } else if (currentTurnIndex == 1) {
      x = 275;
      y = (Constants.SCREEN_HEIGHT - 25) / 2;
    } else if (currentTurnIndex == 3) {
      x = 45;
      y = (Constants.SCREEN_HEIGHT - 25) / 2;
    }
    g.drawImage(chuyenLuotImg, x, y, GameConstants.TOP_HCENTER_ANCHOR);
    text8.drawString2(g, String.valueOf(time), 0xffffff, x, y + 2, GameConstants.TOP_HCENTER_ANCHOR);
  }

  /**
   * Vẽ trường hợp đánh quân bài
   */
  private void drawDanhBai(Graphics g) {
    // Vẽ các quân bài úp
    for (int i = 0; i < soQuanBaiDanhRa; i++) {
      g.drawImage(baiUpImage, GameConstants.SCREEN_WIDTH / 2 - (soQuanBaiDanhRa * 10 + 20) / 2 + i * khoangCachXemBai, GameConstants.SCREEN_HEIGHT / 2 - 40, GameConstants.TOP_LEFT_ANCHOR);
    }
    // Hiển thị các quân bài đánh ra trên màn hình
    for (int i = 0; i < baiDanhRa.size(); i++) {
      drawCardImage(g, NumberUtil.parseInt(baiDanhRa.elementAt(i).toString()), GameConstants.SCREEN_WIDTH / 2 - (baiDanhRa.size() * 10 + 20) / 2 + i * khoangCachXemBai, GameConstants.SCREEN_HEIGHT / 2 - 20, GameConstants.VCENTER_LEFT_ANCHOR, false);
    }

    if (!isCoTheBoLuot) {
      DrawUtils.drawNotification(g, "Bạn không được bỏ lượt này", text8);
    } else if (!isHopLe) {
      g.setColor(0xFFA500);
      DrawUtils.drawNotification(g, "Bài đánh không hợp lệ", text8);
    } else {
      if (!isShow3BichWarning) {
        DrawUtils.drawNotification(g, "Bạn phải đánh bài bé nhất trước", text8);
      }
    }
  }

  private void setState(int state1) {
    if (state1 == DANH_BAI) {
      Vector baiDanh = new Vector();
      String strData = "";
      if (userCards[0].size() > 0) {
        for (int i = 0; i < userCards[0].size(); i++) {
          CardInfo info = (CardInfo) userCards[0].elementAt(i);
          if (info.getQuanChon() != -1) {
            baiDanh.addElement(info);
          }
        }
        for (int i = 0; i < baiDanh.size(); i++) {
          if (i == baiDanh.size() - 1) {
            strData += ((CardInfo) baiDanh.elementAt(i)).getQuanBai();
          } else {
            strData += ((CardInfo) baiDanh.elementAt(i)).getQuanBai() + ":";
          }
        }
      }
      if ((currentTurnIndex == 0) && strData.length() > 0) {
        sendMessageAction(DANHBAI_HEARDER, strData);
      }
    }
    this.state = state1;
  }

  public void doTask() {
    countTime++;
    if (countTime % 10 == 0) {
      if (time > 0) {
        time--;
      }
    }
    
    if (moneyChangeIndex > -1) {
      moneyChangeIndex++;
      if (moneyChangeIndex > 50) {
        moneyChangeIndex = -1;
      }
    }
  }
  
  private void drawMoneyChangeNotification(Graphics g) {
    if (moneyChangeIndex > 0) {
      g.setColor(0xFFA500);
      g.fillRoundRect(GameConstants.SCREEN_WIDTH / 2 - 80, GameConstants.SCREEN_HEIGHT / 2 - 22, 160, 24, 5, 5);
      text8.drawString2(g, moneyChangeMessage, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2 - 20, GameConstants.TOP_HCENTER_ANCHOR);
    }
  }

  private void drawCardImage(Graphics g, int quanBai, int x, int y, int anchor, boolean isRotate) {
    if (cardImges[quanBai] == null) {
for1: for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 13; j++) {
          int index = i * 13 + j - 2;
          index = (index - i * 13 == -2) ? i * 13 + 11 : index;
          index = (index - i * 13 == -1) ? i * 13 + 12 : index;
          if (quanBai != index) {
            continue;
          }
          cardImges[index] = ImageUtil.getImage(Constants.CARD_IMAGE_CATEGORY, (j + 1) + "_" + cardOrder[i] + ".png");
          break for1;
        }
      }
    }
    
    if (!isRotate) {
      g.drawImage(cardImges[quanBai], x, y, anchor);
    } else {
      g.drawImage(ImageUtil.rotate(cardImges[quanBai], 180), x, y, anchor);
    }
  }

  private void sendMessageAction(int header, String data) {
    DataPackage dataPackage = Game.createGamePackage(header);
    dataPackage.putString(data);
    Global.gameActionClient.write(dataPackage);
  }

  private String getThuHang(String number) {
    if ("1".equals(number)) {
      return "Nhất";
    } else if ("2".equals(number)) {
      return "Nhì";
    } else if ("3".equals(number)) {
      return "Ba";
    } else if ("4".equals(number)) {
      return "Bét";
    }
    return "";
  }

  public void onConnectDone() {
  }

  public void onConnectFail() {
  }

  public void onDisconnect() {
  }
  
  public void destroy() {
    initData = null;
    chiaBaiData = null;
    luotChoiData = null;
    isClientInitDone = false;
    
    cardImges = null;
    tableImage = null;
    text8 = null;
    baiUpImage = null;
    arrowImage = null;
    ketQuaImg = null;
    nhatImg = null;
    baiMatSauImages = null;
    chuyenLuotImg = null;
    userCards = null;
    playerNames = null;
    resultIndex = null;
    nguoiThoatGame = null;
    baiDanhRa = null;
    thoi2 = null;
    thoiTuQuy = null;
    kqMoney = null;
    kqTen = null;
    kqThuHang = null;
    cardOrder = null;
  }
}
